Array and Hash

Goals

Many programming languages have data structures such as arrays, and JavaScript is no exception. Today we will dive deeper into what you can do with arrays in JavaScript.

  • Understand the concept of an array.
  • Understand how to create multidimensional arrays in JavaScript programs.Learn how to refer to multidimensional arrays in JavaScript program. Learn how to add , combine, acquire and delete elements.
  • Understand the concept of a hash
  • Understand the relationship between a hash and objects in JavaScript.
  • Understand how to create a hash in JavaScript programs.
  • Understand how to refer to a hash in a JavaScript program.
  • Understand how to add, combine, acquire and delete elements in a hash
  • Understand what constitutes a strong password
  • Understand TLS

Arrays

Array declaration

An array allows you to save a lot of data (called array elements) by delimiting, or splitting, one variable into many. Data is stored in a box in an ordered format. When saving and retrieving data, we refer to the data in the form of the variable name followed by its reference number. In the array, numbers are used for subscripts, and we begin counting from 0. These subscripts are used to tell us which data element within the variable we are referring to.

Using letters, numbers start with 0. Subscript is the value written in brackets.

配列の概念
配列の概念

Methods for generating an array are illustrated below. The following examples all generate the same sequence.

JavaScript

// Method 1
var array = ['hoge', 'fuga'];

// Method 2
var array = new Array('hoge', 'fuga');

// Method 3
var array = Array('hoge', 'fuga');

// パターン4
var array = [];
array[0] = 'hoge';
array[1] = 'fuga';

// array[0] is 'hoge'
// array[1] is 'fuga'

Array manipulation

As mentioned earlier, there are many methods available for manipulating arrays. For example, if you want to concatenate two arrays, do the following.

JavaScript

var array1 = ["Ito", "Suzuki", "Tanaka"];
var array2 = ["Watanabe", "Ito", "Yamamoto"];

var array = array1.concat(array2);

In this example, each array of array 1 and array 2 is generated first, the two are combined at the fourth line, and assigned to a variable called array. As a result, the contents of array are “[” Sato “,” Suzuki “,” Tanaka “,” Watanabe “,” Ito “,” Yamamoto “].

There are various other methods as shown in the table below. However, there are some things that change the underlying sequence (destructive operation) and those that generate new arrays like concat () (non-destructive operation). We must be wary of the difference between the two.

Method Explanation
concat(ary) Constructs a new array concatenated with the array specified by ary and returns it.
join(str) Returns a string obtained by connecting each value of array with delimiter string str.
pop() It returns the element at the end of the array as a value, and then deletes the element.
push(val) Adds the value specified by val as an element to the end of the array.
reverse() Returns the reverse arrangement order of the elements of the array.
shift() It returns the element at the head of the array as a value, and then deletes that element.
slice(start[, end]) Extracts the array from the start to the (end-1)th element.
sort([func]) Sorts the elements in ascending order. You can also specify a function to use for sorting with func.
splice(start, cnt [, rep [, …]]) Replaces elements from start to start + cnt-1 in the array with rep.
toString() Returns a string of elements separated by “,”.
unshift(val) Adds the value specified by val as an element to the beginning of the array.

Also, although not a method, “length” is also a useful property of an array. You can know the number of elements of an array by using length.

Property Explanation
length Returns the number of elements in an array

Hash

Using meaningful strings for subscripts in arrays allows you to quickly retrieve values related to a string. For example, if you create an array with student ID numbers and use the name for that subscript, you can quickly retrieve the student ID number by accessing the array based on the name. Such an arrangement is generally called a hash.

Strictly speaking, there is no concept of a hash in JavaScript, but the same thing can be realized by using an Object. In the example below, the variable obj contains two values ‘taro’ and ‘jiro’, and subscripts (labels) for accessing each are ‘sato’ and ‘suzuki’.

 

JavaScript
// Method 1
var obj = { sato: 'taro', suzuki: 'jiro'};

// Method 2
var obj = { 'sato': 'taro', 'suzuki': 'jiro' };

// Method 3
var obj = {};
obj.sato = 'taro';
obj.suzuki = 'jiro';

// Method 4
var obj = {};
obj['sato'] = 'taro';
obj['suzuki'] = 'jiro';

//  Method 5
var obj = new Object();
obj.sato = 'taro';
obj.suzuki = 'jiro';

// obj['sato'] が 'taro'
// obj['suzuki'] が 'jiro'

Two dimensional arrays

When trying to store data like a spreadsheet, the functions we have seen so far may be insufficient. For example, suppose you have the following data:

Date Opening Price Max Price MIN Price Closing Price
2011/1/10 82.690000 83.540000 82.379900 82.940000
2011/1/17 82.800000 83.489900 81.819900 82.580000

This is exchange rate data for the weekly dollar yen in 2011. How can we handle this data? One possible way is to treat each column as an array.


<figure class="frame"><pre>var date =  ["2011年1月10日", "2011年1月17日", ...];
var start = [82.690000, 82.800000, ...];
var high =  [83.540000, 83.489900, ...];
var low =   [82.379900, 81.819900, ...];
var end =   [82.940000, 82.580000, ...];

Certainly this still can handle data, but there is a better way. We can use a two-dimensional array for storing data by columns and rows as shown in the table.


var usdjpy = [

<figure class="frame"><pre>  ["2011/1/10",82.690000,83.540000,82.379900,82.940000],
  ["2011/1/17",82.800000,83.489900,81.819900,82.580000],
  ...
];

In this example, the date, the opening price, the max price, the min price, the closing price are arranged as one row, and the array for every week is made as a column. In other words, “[” January 10, 2011 “, 82.69, 83.54, 82.3799, 82.94]] is also one array, and the whole table gathered is also an array. In the above example, the variable usdjpy contains an array within an array, or a two-dimensional array.

Now, how do we use the two dimensional array we just created? It is not difficult to use once we understand how the arrays are arranged within the 2D array. For example, to use the second column of the first row, we refer to it as”usdjpy [0] [1]”. Since the array starts from the 0th element, the subscript representing the first line is 0 and the subscript representing the second column is 1.


<figure class="frame"><pre>var usdjpy = [
  ["2011/1/10",82.690000,83.540000,82.379900,82.940000],
  ["2011/1/17",82.800000,83.489900,81.819900,82.580000]
];
 
alert(usdjpy[0][1]);

When actually executing the above program, the number “82.69” is displayed with an alert.

Security

When using computer networks, knowing about security is very important. In this section, your understanding of arrays is crucial to acquiring skills related to security.

Creating a strong password

One of the security topics that is familiar to you is a password. Passwords are used in various situations, such as logging onto a computer, or connecting to a server. When making a password, it is often said that you have to make it more than a certain length, you should mix capital letters and lower case letters, you should include numbers and symbols, and not use the words in the dictionary. Why is this? Let’s explore.

Brute force attacks

What method would you test if you were told that a certain password was broken? Perhaps the most common method you may think of is trying random combinations of numbers and letters till you get the right password. This is a lengthy process, but it is an effective means when the password is short. Therefore, using such a means is called brute force attack.

Have you ever seen a key of the type shown below? This key has numbers 0 to 9 written in each ring, you can open the key by matching the three numbers.

key

If you know that it is a three-digit password of numbers from 0 to 9, how long will it take for the computer to solve that password? See the next program. In this program, the time is measured before and after the for loop of the triple loop, and the difference, that is, the time taken is displayed by alert (). Numbers from 000 to 999 are displayed in the three level nested loop portion. It can be confirmed that counting from 0 to 999 takes little time for a computer.

HTML

<input type="button" value="Brute force attack on three digit number, each digit is from 0~9" onclick="n3()">
<input type="text" id="text080201" value="000">

JavaScript

function n3() {
    var str = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    var ele = document.getElementById("text080201");

    var t_start = (new Date).getTime();

    for (var i=0; i&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; i++) {
        for (var j=0; j&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; j++) {
            for (var k=0; k&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; k++) {
                ele.value = str[i] + str[j] + str[k];
            }
        }
    }

    var t_end = (new Date).getTime();

    alert("Time Taken: " + (t_end - t_start) + "ms");
}

As you can see, the time taken for the computer to count from 0 to 999  is very little. For this reason, passwords with short character strings of only numbers are not recommended.

So how will it change when you use lower case alphabets?

HTML

&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;input type="button" value="Brute force attack on three digit number, each digit is from 0~9 and lower case a~z" onclick="na3()"&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;input type="text" id="text080202" value="000"&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

JavaScript

function na3() {
    var str = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
               "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
               "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
    var ele = document.getElementById("text080202");

    var t_start = (new Date).getTime();

    for (var i=0; i&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; i++) {
        for (var j=0; j&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; j++) {
            for (var k=0; k&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; k++) {
                ele.value = str[i] + str[j] + str[k];
            }
        }
    }

    var t_end = (new Date).getTime();

    alert("Time taken:" + (t_end - t_start) + "ms");
}

We can now confirm that the second password generated from alphabets and numbers took longer to crack.

Dictionary Attack

Then, is it safe to just increase the type of letters or increase the number of digits? Not really. If you use a common word as a password, you may unexpectedly get your password hacked. In an attack called a dictionary attack, the attacking side has a dictionary and has tried each word in it till they matched your password.

For example, suppose that there is a character string "university". Since there are 10 characters, it takes a reasonable amount of time in brute force attack. However, using a dictionary attack, the hacker can arrive at the password a lot sooner in their iterations. The number of words in the English dictionary is at most in the order of a few hundred thousands. Let's estimate a little more and try it with a password using a one million word dictionary. This will take the same amount of time as trying a password of 6 digits (000000 - 9999999), which is not a lot of time for computers.

For these reasons, when attaching a password, it is said that "you must make it longer than a certain amount, you should mix capital letters and lower case letters, you should include numbers and symbols, and not use the words in the dictionary.

Web page password authentication

When you are accessing a web page, you may be prompted for a password. This is made possible using functions called Basic Authentication and Digest Authentication. Both Basic Authentication and Digest Authentication authenticate users with ID and password pairs, but in the case of Basic Authentication, unencrypted passwords flow through the network. For this reason, Digest Authentication should be used as much as possible. Previously, some browsers did not support Digest Authentication, but now almost all browsers support it.

In addition, it is also possible to encrypt the communication path itself by using TLS (described later). In this case, the password will flow through the encrypted communication path even in Basic Authentication.

The basic usage of Digest Authentication is to ask for an ID / password to access under a certain directory. For example, ask for ID / password when accessing under the directory public_html / info 2/08, that is, accessing https://web.sfc.keio.ac.jp/~ [login name] / info 2/08 / In order to do so, you need to create a file called public_html / info2 / 08 / .htaccess. In public_html / info2 / 08 / .htaccess, write the following contents. Please note that you put a blank line at the end.

 

AuthUserFile	/home/[loginName]/.htdigest
AuthName	"Members Only"
AuthType	Digest
require 	valid-user
 

After that, create a Digest file. A Digest file is created by launching a terminal as follows. Here, the line starting from "$" is part of the line for input. However, there is no need to enter "$" at the prompt.

$ /usr/sbin/htdigest -c ~/../.htdigest "Members Only" [userName1]
Adding password for [userName1] in realm Members Only.
New password:
Re-type new password:
$ /usr/sbin/htdigest ~/../.htdigest "Members Only" [userName2]
Adding password for [userName2] in realm Members Only.
New password:
Re-type new password:

"- c" in the first line specifies to create a new file. When adding the second and subsequent users, do not specify "-c". For [user name 1] [user name 2], specify the user name you want to use for login. Then you will be prompted for a password so enter twice. This will create a Digest file.

For more details, please refer to http://www.sfc.itc.keio.ac.jp/en/network_web_server.html.

TLS

Previously, in order to access the created Web page, we use a URL like "http: // ...". This shows that you use plain HTTP to access the web. However, in plain HTTP, communication is not encrypted, and if communication is intercepted, communication contents may be eavesdropped.

To solve this problem, we use Transport Layer Security (TLS). In the past, a technology called Secure Sockets Layer (SSL) was used, but now a more sophisticated TLS that supports strong encryption has been developed. However, even though TLS is actually used in the world, many websites still call it  "SSL communication", so it can be a little confusing.

When accessing the Web using TLS, use "https: // ..." instead of "http: // ...". The last "s" indicates that TLS is used. By specifying "https: // ...", the version of the protocol actually used between the Web server and the Web browser is adjusted, and the encrypted communication path is established.

 

https

Generally when a TLS connection is established, a server called "server certificate" is sent from the server side to the client side. For checking the server certificate, a public key cryptosystem cipher is used. Characteristics of public key cryptography are as follows. In the public key cryptosystem, a publicly-known key called a public key and a key pair known only to the user called a secret key are used. A document encrypted with a secret key can be decrypted with a public key, and a document encrypted with a public key can be decrypted with only a secret key. For this reason, when viewing a document encrypted with a secret key, it can be confirmed that only the person who has a secret key made the encrypted sentence. Conversely, documents encrypted with a public key can only be decrypted by a person with a secret key.

In order to check if the communication partner is the intended server indeed, we need to confirm the "server certificate". An organization called certification authority signs (encrypts) it with a secret key. Since the public key of the certificate authority is widely distributed, anyone can confirm (decrypt) whether the "server certificate" sent using the key is correct or not. The certificate authority is managed in a hierarchical structure, and the public key of the certificate authority, which is a major part of it, is distributed across all browsers.

Exercise 8-

Create a simple fortune teller program using arrays. The JavaScript skeleton is as follows.

function mikuji(){
  var unsei = new Array("Good Luck","Medium Luck","Moderate Luck","Little Luck","No luck","Bad Luck","Disaster");
  var uranau = /* Write here */;

  document.getElementById("res").innerHTML = /* Write here */;
}

Exercise 8-

Create a program that simulates the three digit brute force attack shown in the above example and displays the time taken.

Exercise 8-

Create a program that tells you the time you spent trying a brute force attack with 3 digits of alphanumeric characters using only lowercase letters.

Exercise 8-

Create a program that displays alphanumeric three-digit brute-force attacks using both uppercase letters and lowercase letters and displays the time taken in the text area.

Exercise 8-

Create a program that shows the 6 digit brute force attack and displays the time taken in the text area. The time taken is the same as that for a dictionary attack using a dictionary of 1 million words.

Exercise 8-

Certification authorities are the agencies that issue certificates, and in many cases are private corporations. Also, because the certificate is an electronic file, it costs very little to generate. This means that getting into such a business could be very profitable, however this is not true. Think about why it is difficult to launch a certificate authority, and create a web page showing that idea.

Also make Digest Authentication so that you can access it on ID: info2, Password: Keio # University